from Tkinter import *
import xmlrpclib
from time import clock, time

server = xmlrpclib.ServerProxy("http://192.168.1.2:8888")


def userType(user):
    return server.userType(user)

def newName(oldUname,newUname):
    return server.newName(oldUname,newUname)
def banUser(name):
    server.banUser(name)

class MyDetails:
    def __init__(self,parent,uname):
        self.mainframe=Frame(parent)
        frame=Frame(self.mainframe)
        frame.grid(row=0,column=0)
        self.data={} ##data[1] - new name, [2] - new password
        self.data[1]=""
        self.data[2]=""
        self.done=0
        self.uname=uname ##used to search the database fo the old pass
        ##Title labels
        self.changeName=Label(frame,text="Change your name",background = 'LightGoldenrod1')
        self.changePassword=Label(frame,text="Change your password",background = 'LightGoldenrod1')
        self.changeName.grid(row=0,column=0,columnspan=4,sticky=NSEW)
        self.changePassword.grid(row=2,column=0,columnspan=4,sticky=NSEW)
        ##entries and labels
        self.newName=Label(frame,text="New name:")
        self.oldPass=Label(frame,text="Old Password:")
        self.newPass=Label(frame,text="New Password:")

        self.newNameEntry=Entry(frame,width=35)
        self.oldPassEntry=Entry(frame,width=35,show="*")
        self.newPassEntry=Entry(frame,width=35,show="*")
        self.newName.grid(row=1,column=0)
        self.newNameEntry.grid(row=1,column=1,columnspan=3)
        self.oldPass.grid(row=3,column=0)
        self.oldPassEntry.grid(row=3,column=1,columnspan=3)
        self.newPass.grid(row=4,column=0)
        self.newPassEntry.grid(row=4,column=1,columnspan=3)
        self.mainframe.grid()
        self.mainframe.master.title("Change details")
        ##button
        self.changeName=Button(frame,text="Change Name",command=self.chName)
        self.changePass=Button(frame,text="Change Password",command=self.chPass)
        self.changeAll=Button(frame,text="Change all",command=self.chAll)
        self.exitBtn=Button(frame,text="Exit",command=self.exitDet)
        self.changeName.grid(row=5,column=0,sticky=NSEW)
        self.changePass.grid(row=5,column=1,sticky=NSEW)
        self.changeAll.grid(row=5,column=2,sticky=NSEW)
        self.exitBtn.grid(row=5,column=3,sticky=NSEW)
        ##warnings label
        self.warningLabel=Label(frame,text="")
        self.warningLabel.grid(row=6,column=0,columnspan=4,sticky=NSEW)        
    
    def exitDet(self):
        self.done=1

    def chName(self):
        if self.newNameEntry.get()!="":
            if newName(self.uname,self.newNameEntry.get())==1:
                self.data[1]=self.newNameEntry.get()
                self.done=1
            else:
                self.warningLabel.configure(text="Name already in use",background = 'DarkRed')
                self.warningLabel.update_idletasks()
                self.done=0

        
    def chPass(self):
        if self.newPassEntry.get()!="":
            if  server.newPassword(self.oldPassEntry.get(),self.data[2],self.uname)==1:
                self.data[2]=self.newPassEntry.get()
                self.done= 1          
            else:
                self.warningLabel.configure(text="Password incorect",background = 'DarkRed')
                self.warningLabel.update_idletasks()
                self.done=0

    def chAll(self,*ignore):
        if self.newNameEntry.get()!="" and self.newPassEntry.get()!="":
            self.data[2]=self.newPassEntry.get()
            server.newPassword(self.oldPassEntry.get(),self.data[2],self.uname)
            self.data[1]=self.newNameEntry.get()
            server.newName(self.uname,self.data[1])
            self.done=1
        else:
            self.warningLabel.configure(text="Name or password incorect/not inserted",background = 'DarkRed')
            self.warningLabel.update_idletasks()
            self.done=0            

            
##GUI login interface
class MyLogin:
    def __init__(self,parent):
        self.mainframe=Frame(parent)
        frame=Frame(self.mainframe)
        frame.grid(row=0,column=0)
        self.UserLabel=Label(frame,text="User:")
        self.PassLabel=Label(frame,text="Password:")
        self.TextLabel=Label(frame,text="")
        self.UserEntry=Entry(frame,width=30)
        self.PassEntry=Entry(frame,show="*",width=30)
        self.LogIn=Button(frame,text="LogIn",command=self.DoLogIn)
        self.Reg=Button(frame,text="Register",command=self.Register)
        ##Grid set up
        self.UserLabel.grid(row=0,column=0,columnspan=2,sticky=NSEW)
        self.PassLabel.grid(row=1,column=0,columnspan=2,sticky=NSEW)
        self.TextLabel.grid(row=3,column=0,columnspan=3,sticky=NSEW)
        self.UserEntry.grid(row=0,column=2,sticky=NSEW)
        self.PassEntry.grid(row=1,column=2,sticky=NSEW)
        self.LogIn.grid(row=2,column=1,sticky=NSEW)
        self.Reg.grid(row=2,column=2,sticky=W)
        self.mainframe.grid()
        self.mainframe.master.title("LonIn or create account")
        ##Set confirm state
        self.confirm=False

    ##activate on selecting the log in option
    def DoLogIn(self,*ignore):
        ##check if the details are correct or is banned
        ##status - {0 - wrong details, 1 - correct details, 2- banned user}
        status=server.checkUser(self.UserEntry.get(),self.PassEntry.get())
        ##if stauts - 1 start the count down
        if status==1:
            self.logInTimer()
            self.confirm=True
            return 0
        ##if status 2 print that the user is banned
        if status==2:
            self.TextLabel.configure(text="Login failed: You are banned",background = 'DarkRed')
            self.TextLabel.update_idletasks()
            self.UserEntry.delete(0,END)
            self.PassEntry.delete(0,END)
            return 0
        ##if status 0 print that the details are wrong
        self.TextLabel.configure(text="Login failed: Wrong user/password",background = 'DarkRed')
        self.TextLabel.update_idletasks()
        self.UserEntry.delete(0,END)
        self.PassEntry.delete(0,END)
        self.confirm=False

    ##register an user
    def Register(self):
        ##check to see if the user exists
        ##the check is case sensitive so the user CoCo will not be allowed if Coco exists
        if (server.addUser(self.UserEntry.get(),self.PassEntry.get())==0):
            self.TextLabel.configure(text="Please select a different name",background = 'DarkRed')
            self.TextLabel.update_idletasks()
            self.confirm=False
            return False
        ##if the username is free print the the account has been created
        self.TextLabel.configure(text="Account created, you can now log in",background="LightSeaGreen")
        self.TextLabel.update_idletasks()
        self.UserEntry.delete(0,END)
        self.PassEntry.delete(0,END)
        return True

    ##timer activated if the login details are correct
    def logInTimer(self):
        now=time()
        while int(time()-now)!=3:
            self.TextLabel.configure(text="Loging in {0}".format(3-int(time()-now)),background="LightSeaGreen")
            self.TextLabel.update_idletasks()            

        
def log():
    log_win=Tk()
    login=MyLogin(log_win)
    log_win.bind("<Return>",login.DoLogIn)
    while login.confirm==False:
        log_win.update()
    user=login.UserEntry.get()
    log_win.destroy()
    server.newName(user,user)
    return (user)

def details(uname):
    det_win=Tk()
    details=MyDetails(det_win,uname)
    det_win.bind("<Return>",details.chAll)
    while details.done==0:
        det_win.update()
    data=details.data
    det_win.destroy()
    return data

    
